/**
 * Created by weng on 2018/1/16.
 */

var sea = require('../common/sea');
var request = require('../common/Request');
// let {RequestPost} = import('../common/Request')
//
const utils = require("../common/utils")

let RequestPost = request.RequestPost
const sqlOrm = require('../common/sqlModel');
const taobao = require('../controllers/taobao');
let commonModel = require('../common/commonModel');
const SMSClient = require('@alicloud/sms-sdk');
var uuid = require("node-uuid");
var fs = require("fs");
const accessKeyId = 'LTAIcFJXeQLLZ2dT';
const secretAccessKey = 'MWC5aVCuhGkssg2uwGnqbMpwnUY7MZ'
const mySignName = '淘饭饭';

let Url = 'http://139.224.115.234:8081/';
const smsClient = new SMSClient({accessKeyId, secretAccessKey});
let VipUrl = ['http://www.fzjygw.top/','http://wengchaoan.top:8083/','http://wengchaoan.top:8083/'];


// VipUrl = VipUrl[Math.floor(Math.random() * VipUrl.length)];
const answerUrl = 'http://www.jinyupay.top:8081/'
const transferUrl = 'http://127.0.0.1:33333/v01/paycenter/transfer'
const rate = require("../common/config.json").rate
const LocalUrl = require("../common/config.json").LocalUrl

class Register {
    async register(req, res, body ,cb) {
        try {

            // let signData = req.body.data;
            // let chechInfo = chechSing(signData)
            // if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo =body
            let account = signDecodedInfo.phone;
            let passWd = signDecodedInfo.passWd;
            let phone = signDecodedInfo.phone;
            let code = signDecodedInfo.code;
            let MacId = signDecodedInfo.MacId;
            let id = signDecodedInfo.shareId;
            console.log("share",id == null)
            console.log("share",id == "null")
            console.log("share",!id)

            // console.log("share",shareId.length)
            let money =  0;
            var shareId
            if(!id || id.length <= 0 || id == "null"){
                shareId = 0
            } else {
                var shareAccount =  await sqlOrm.app_account.findAsync({id:id})
                if(shareAccount.length <= 0){
                    return cb({code: 500, msg: "分享者不存在"});
                }
                shareId = shareAccount[0].account
                money = global.initMoney
            }
            if (!MacId || !account || !passWd || !phone || !code)
                return cb({code: 500, msg: "参数不足"});

            let VerCode = await sqlOrm.app_phone_code.findAsync({phone});
            if (VerCode.length <= 0) {
                return cb({code: 500, msg: "验证码错误"});
            }
            if (VerCode[0].code != code) {
                return cb({code: 500, msg: "验证码错误"});
            }

            let Account = await sqlOrm.app_account.findAsync({account});
            console.log("Account", Account.length);
            /// 没有账号就添加
            if (Account.length <= 0) {
                let mm =await taobao.getadzoneIdInfo(account,false);
                console.log("mm is",mm)
                let time = new Date().getTime();
                let aliveTime = 0;
                let status = -1;

                await sqlOrm.app_account.createAsync({
                    account,
                    MacId,
                    passWd,
                    phone,
                    createTime: new Date(),
                    updateTime: new Date(),
                    time: time,
                    aliveTime: aliveTime,
                    status: status,
                    mm:mm,
                    time:"",
                    shareTimes:0,
                    shareId:"",
                    cutNum:0,
                    signUpTime:"",
                    money:money,
                    moneyBake:0,
                    needBackMoney:0,
                    icon:"",
                    nick:"",
                    sex:"0",
                    borth:"",
                    shareId:shareId,
                });
                if (shareId !=0){
                    sqlOrm.shareInfo.createAsync({shareId:account,masterId:shareId,time:new Date().getTime()})
                }
                let VipUrlInfo = VipUrl[Math.floor(Math.random() * VipUrl.length)];
                let AccountInfo = await sqlOrm.app_account.findAsync({account});
                let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify({id: AccountInfo[0].id}));
                let token = new Buffer(JsonString).toString('base64');

                let url = "http://wengchaoan.top:8081/v01/account/addVipTimes";
                let obj = {};
                obj.phone = phone;
                obj.time = 15;
                let sign = sea.encrypt(sea.key, sea.vi, JSON.stringify(phone));
                obj.sign = sign;
                let macInfo = await sqlOrm.app_account.countAsync({MacId});
                if(macInfo <= 0){
                    let info = await RequestPost(url,obj);
                    console.log("3333333333333333333",info)
                }

                return cb({
                    code: 200,
                    msg: "注册成功",
                    token,
                    vipUrl: VipUrlInfo,
                    url: Url,
                    id: AccountInfo[0].id,
                    account: AccountInfo[0].account,
                    status: AccountInfo[0].status,
                    aliveTime: parseInt(AccountInfo[0].aliveTime),
                    shareTimes: AccountInfo[0].shareTimes,
                    time: AccountInfo[0].time,
                    golden: AccountInfo[0].golden,
                });
            } else {
                return cb({code: 500, msg: "账号已经存在"});
            }
        } catch (e) {
            console.error("getTime err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async changePassWd(req, res, cb) {
        try {

            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo

            let MacId = signDecodedInfo.MacId;
            let account = signDecodedInfo.phone;
            let passWd = signDecodedInfo.passWd;
            let phone = signDecodedInfo.phone;
            let code = signDecodedInfo.code;

            if (!MacId || !account || !passWd || !phone || !code)
                return cb({code: 500, msg: "参数不足"});

            let VerCode = await sqlOrm.app_phone_code.findAsync({phone});

            if (VerCode.length <= 0) {
                return cb({code: 500, msg: "验证码错误"});
            }
            if (VerCode[0].code != code) {
                return cb({code: 500, msg: "验证码错误"});
            }
            let Account = await sqlOrm.app_account.findAsync({account});
            console.log("Account", Account.length);
            /// 没有账号就添加
            if (Account.length <= 0) {
                return cb({code: 500, msg: "账号不存在"});
            } else {
                Account[0].passWd = passWd;
                Account[0].saveAsync();
                return cb({code: 200, msg: "账号修改成功"});
            }
        } catch (e) {
            console.error("getTime err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async doLoginAccount(req, res, cb) {
        try {

            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo


            let MacId = signDecodedInfo.MacId;
            let account = signDecodedInfo.account;
            let passWd = signDecodedInfo.passWd;

            if (!MacId || !account || !passWd)
                return cb({code: 500, msg: "参数不足", url: Url});

            let Account = await sqlOrm.app_account.findAsync({account, passWd});

            if (Account.length <= 0) {
                return cb({code: 500, msg: "账号密码不正确", url: Url});
            }

            let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify({id: Account[0].id}));
            let token = new Buffer(JsonString).toString('base64');
            // global.app_account[token] = Account[0];
            Account[0].MacId = MacId;
            Account[0].saveAsync();
            let VipUrlInfo = VipUrl[Math.floor(Math.random() * VipUrl.length)];

            if (Account[0].status == -1) {

                // cb({code: 200, url: Url, aliveTime: 0, time: Account[0].time , msg: "非vip",status:-1});

                return cb({
                    code: 200,
                    msg: "登陆成功",
                    token,
                    vipUrl: VipUrlInfo,
                    url: Url,
                    id: Account[0].id,
                    account: Account[0].account,
                    status: Account[0].status,
                    aliveTime: 0,
                    shareTimes: Account[0].shareTimes,
                    time: Account[0].time,
                    golden: Account[0].golden,
                });


            } else if (JSON.parse(Account[0].time) + JSON.parse(Account[0].aliveTime) * (1000 * 60 * 60 * 24 ) < new Date().getTime()) {


                return cb({
                    code: 200,
                    msg: "登陆成功",
                    token,
                    vipUrl: VipUrlInfo,
                    url: Url,
                    account: Account[0].account,
                    id: Account[0].id,
                    status: Account[0].status,
                    aliveTime: 0,
                    shareTimes: Account[0].shareTimes,
                    time: Account[0].time,
                    golden: Account[0].golden,

                });


                // cb({code: 200, url: Url, aliveTime: parseInt(Account[0].aliveTime), time: Account[0].time , msg: "VIP过期",});
            } else {
                // let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify({id: Account[0].id}));
                //  let token = new Buffer(JsonString).toString('base64');


                return cb({
                    code: 200,
                    msg: "登陆成",
                    token,
                    vipUrl: VipUrlInfo,
                    url: Url,
                    account: Account[0].account,
                    id: Account[0].id,
                    status: Account[0].status,
                    aliveTime: parseInt(Account[0].aliveTime),
                    shareTimes: Account[0].shareTimes,
                    time: Account[0].time,
                    golden: Account[0].golden
                });
            }
        } catch (e) {
            console.error("getTime err is", e);
            return cb({code: 500, msg: "err", url: Url})
        }
    }

    async doLoginID(req, res, cb) {
        try {
            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo

            let MacId = signDecodedInfo.MacId;
            let token = signDecodedInfo.token;

            if (!MacId || !token)
                return cb({code: 500, msg: "参数不足", url: Url});

            if (token == -1) {
                return cb({code: 200, url: Url, msg: "登陆成功", token: token});
            }

            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            // let id = new Buffer(JsonString).toString('base64');
            console.log("JsonString", JsonString)
            let VipUrlInfo = VipUrl[Math.floor(Math.random() * VipUrl.length)];

            if (JsonString.code == 200) {
                const decodedInfo = JSON.parse(JsonString.decoded);
                console.log("decodedInfo", decodedInfo)
                const id = decodedInfo.id;
                let AccountInfo = await sqlOrm.app_account.findAsync({id});
                console.log("length", AccountInfo.length)
                if (AccountInfo.length > 0) {
                    if (AccountInfo[0].MacId !== MacId) {
                        return cb({code: 500, msg: "账号在其他设备登陆"});
                    }
                    let userMine = AccountInfo[0]
                    let money  = userMine.money; //金额
                    let account = userMine.account; //账号
                    let channel = userMine.mm // 渠道id
                    let needBackMoney = userMine.needBackMoney // 待返利金额
                    let moneyBake = userMine.moneyBake // 已经返利金额
                    let nick = userMine.nick // 昵称
                    let borth = userMine.borth //  出生
                    let icon = LocalUrl + userMine.icon  //头像
                    let sex = userMine.sex //  性别
                    let aliAccount = userMine.aliAccount //  性别

                    // 暂时不考虑 vip的问题，直接返回信息
                    return cb({
                        code: 200,
                        msg: "登陆成功",
                        token,
                        vipUrl: VipUrlInfo,
                        url: Url,
                        id: AccountInfo[0].id,
                        account: AccountInfo[0].account,
                        status: AccountInfo[0].status,
                        aliveTime: 0,
                        shareTimes: AccountInfo[0].shareTimes,
                        time: AccountInfo[0].time,
                        money,
                        channel,
                        needBackMoney,
                        moneyBake,
                        nick,
                        borth,
                        icon,
                        sex,
                        aliAccount,
                    });
                    //
                    // if (AccountInfo[0].status == -1) {
                    //
                    //     return cb({
                    //         code: 200,
                    //         msg: "登陆成功",
                    //         token,
                    //         vipUrl: VipUrlInfo,
                    //         url: Url,
                    //         account: AccountInfo[0].account,
                    //         status: AccountInfo[0].status,
                    //         aliveTime: 0,
                    //         shareTimes: AccountInfo[0].shareTimes,
                    //         time: AccountInfo[0].time,
                    //         money,
                    //         channel,
                    //         needBackMoney,
                    //         moneyBake,
                    //         nick,
                    //         borth,
                    //         icon,
                    //         sex,
                    //     });
                    // }
                    //
                    // if (JSON.parse(AccountInfo[0].time) + JSON.parse(AccountInfo[0].aliveTime) * (1000 * 60 * 60 * 24 ) < new Date().getTime()) {
                    //
                    //     return cb({
                    //         code: 200,
                    //         msg: "登陆成功",
                    //         token,
                    //         vipUrl: VipUrlInfo,
                    //         url: Url,
                    //         account: AccountInfo[0].account,
                    //         status: AccountInfo[0].status,
                    //         aliveTime: 0,
                    //         shareTimes: AccountInfo[0].shareTimes,
                    //         time: AccountInfo[0].time,
                    //         golden: AccountInfo[0].golden
                    //     });
                    // }
                    //
                    // return cb({
                    //     code: 200,
                    //     msg: "登陆成功",
                    //     token: token,
                    //     vipUrl: VipUrlInfo,
                    //     url: Url,
                    //     account: AccountInfo[0].account,
                    //     status: AccountInfo[0].status,
                    //     aliveTime: parseInt(AccountInfo[0].aliveTime),
                    //     shareTimes: AccountInfo[0].shareTimes,
                    //     time: AccountInfo[0].time,
                    //     golden: AccountInfo[0].golden
                    // })
                } else {
                    return cb({code: 500, msg: "账号不存在", url: Url});
                }
            } else {
                return cb({code: 500, msg: "token错误", url: Url});
            }
        }
        catch (e) {
            console.error("getTime err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async getCode(req, res, body,cb) {
        try {

            // let signData = req.body.data;
            // let chechInfo = chechSing(signData)
            // if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = body
            let MacId = signDecodedInfo.MacId;
            let phone = signDecodedInfo.phone;
            let sign = signDecodedInfo.sign;
            if (!MacId || !sign)
                return cb({code: 500, msg: "参数不足"});

            const codeInfo = await getrandomNumber(6);
            const code = codeInfo.info;
            const msgInfo = JSON.stringify({code});
            const sentMsg = await sentMsgInfo(phone, 'SMS_128840469', msgInfo);
            const time = new Date().getTime()
            if (sentMsg.code == 200) {
                let codeInfo = await sqlOrm.app_phone_code.findAsync({phone});
                console.log("3433333333333333333", code)
                if (codeInfo.length <= 0) {
                    await sqlOrm.app_phone_code.createAsync({phone, code, time});
                } else {
                    codeInfo[0].code = code;
                    codeInfo[0].time = time;
                    codeInfo[0].saveAsync();
                }
                return cb({code: 200, msg: "发送成功"})
            } else {
                return cb({code: 500, msg: "发送短信失败，请稍后重试"})
            }
        } catch (e) {
            console.error("getCode err is", e);
            if (!e) e = "err"
            return cb({code: 500, msg: "err"})
        }
    }

    async getItemList(req, res, cb) {
        try {

            let itemList = await sqlOrm.itemList.findAsync({status: 1});
            if (itemList.length > 0) {
                return cb({code: 200, itemList: itemList, msg: "获取物品列表成功"})
            } else {
                return cb({code: 200, itemList: [], msg: "获取物品列表为空"})
            }
        } catch (e) {
            console.error("getItemList err is", e);
            return cb({code: 500, msg: e})
        }
    }

    async sureOrder(req, res, cb) {
        try {
            let orderId = req.body.cporder;
            let amount = req.body.amount;
            let orderIdInfo = await sqlOrm.appOrder.findAsync({orderId: orderId});

            if (orderIdInfo.length <= 0) {
                console.error("没有订单信息 err is", req.body)
                return cb({code: 500, msg: "没有订单信息"})
            } else {
                //console.log("amountamountamountamountamountamountamount",amount,orderIdInfo[0].money, amount,orderIdInfo[0].money)
                if (orderIdInfo[0].money > amount) {
                    console.error("金额不对 err is", req.body)
                    return cb({code: 500, msg: "金额不对"})

                }
                if (orderIdInfo[0].status == 1) return cb({code: 200, msg: "成功，已经修改"})

                let itemId = orderIdInfo[0].itemId
                let accountId = orderIdInfo[0].accountId;
                orderIdInfo[0].status = orderIdInfo[0].status + 1
                orderIdInfo[0].saveAsync();
                let itemList = await sqlOrm.itemList.findAsync({id: itemId});
                let time = itemList[0].time;
                let orderType = itemList[0].type;
                let golden = itemList[0].golden;
                let Account = await sqlOrm.app_account.findAsync({id: accountId});
                if (Account.length <= 0) {
                    console.error("没有账号信息 err is", req.body)
                    return cb({code: 500, msg: "没有账号信息"});
                }
                if (orderType == 2) {
                    /// 充值金币
                    Account[0].golden += golden
                } else {
                    let needTime = new Date().getTime();
                    if (Account[0].status == 0) {
                        let lessTime = JSON.parse(Account[0].aliveTime) * 1000 * 60 * 60 * 24 + JSON.parse(Account[0].time) - JSON.parse(needTime);
                        console.error("lessTime err is", lessTime);
                        if (lessTime > 0) {
                            needTime = JSON.parse(new Date().getTime()) + lessTime
                        }
                    }
                    Account[0].aliveTime = time
                    Account[0].time = needTime // new Date().getTime();
                    Account[0].status = 0
                }
                Account[0].updateTime = new Date()
                Account[0].saveAsync();
                return cb({code: 200, msg: "成功"})
            }
        } catch (e) {
            console.error("sureOrder err is", req.body, e);
            return cb({code: 500, msg: e, info: "err"})
        }
    }

    async getOrder(req, res, cb) {
        try {
            /// 订单号
            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo

            let itemId = signDecodedInfo.itemId;
            let token = signDecodedInfo.token;

            if (!itemId || !token)
                return cb({code: 500, msg: "参数不足", url: Url});

            if (token == -1) {
                return cb({code: 500, msg: "token错误"});
            }
            let orderId = uuid.v4().substring(0,31);
            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            console.log("JsonString", JsonString)
            if (JsonString.code != 200) {
                return cb({code: 200, url: Url, msg: "登陆成功", token: token});
            }

            const decodedInfo = JSON.parse(JsonString.decoded);
            const accountId = decodedInfo.id;

            let itemList = await sqlOrm.itemList.findAsync({id: itemId});
            if (itemList.length <= 0) {
                return cb({code: 500, msg: "物品ID错误"})
            }

            let money = itemList[0].realMoney;
            await sqlOrm.appOrder.createAsync({
                accountId,
                orderId,
                itemId,
                money,
                status: 0
            });
            return cb({code: 200, orderId: orderId, money: money, msg: "下单成功"})

        } catch (e) {
            console.error("getOrder err is", e);
            console.error("req.body err is", req.body);
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async protocol(req, res, cb) {
        try {

            return cb({code: 200, file: fs.readFileSync("../common/xy.html")})

        } catch (e) {
            console.error("getOrder err is", e);
            console.error("req.body err is", req.body);
            if (!e) e = "err"
            return cb({code: 500, msg: e})
        }
    }

    async share(req, res, cb) {
        try {
            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo

            //let phone = signDecodedInfo.phone;
            let token = signDecodedInfo.token;
            if (!token) return cb({code: 500, msg: "参数不足"})
            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            // let id = new Buffer(JsonString).toString('base64');
            console.log("JsonString", JsonString)
            if (JsonString.code != 200) {
                return cb({code: 500, msg: "签名错误"})
            }

            const decodedInfo = JSON.parse(JsonString.decoded);
            console.log("decodedInfo", decodedInfo)
            const id = decodedInfo.id;
            let AccountInfo = await sqlOrm.app_account.findAsync({id});
            if (AccountInfo.length <= 0)  return cb({code: 500, msg: "没有账号信息"})

            let phone = AccountInfo[0].phone;

            let shareFlag = 0;

            let Account = await sqlOrm.app_account.findAsync({phone});
            for (var ac of Account) {
                if (ac.shareTimes < 1) {
                    if (!ac.shareTimes)
                        ac.shareTimes = 0
                    ac.shareTimes += 1

                    ac.saveAsync()
                } else {
                    shareFlag = 1
                }
            }


            if (!shareFlag) {
                AccountInfo[0].aliveTime = JSON.parse(AccountInfo[0].aliveTime) + 1;
                AccountInfo[0].saveAsync();
                return cb({code: 200, msg: "分享成功"})
            } else {
                return cb({code: 500, itemList: [], msg: "已经分享过了"})
            }
        } catch (e) {
            console.error("share err is", e);
            return cb({code: 500, msg: "error"})
        }
    }

    async getAnswerUrl(req, res, cb) {
        try {
            let body = req.query;

            let token = body.token;
            let roomType  = body.roomType;
            if (!token){
                return cb({code: 500, url: "", msg: "参数错误", token: token});
            }
            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            if (JsonString.code != 200) return cb({code: 500, url: "", msg: "签名错误", token: token});

            const decodedInfo = JSON.parse(JsonString.decoded);
            console.log("decodedInfo", decodedInfo)
            const id = decodedInfo.id;
            let AccountInfo = await sqlOrm.app_account.findAsync({id});
            let roomInfo = await sqlOrm.roomInfo.findAsync({type:roomType});
            if(roomInfo.length <= 0) return cb({code: 500, url: "", msg: "房间类型不对", token: token});
            if(AccountInfo[0].golden < roomInfo[0].golden) return cb({code: 500, url: "", msg: "金币不足", token: token});
            return cb({code: 200, msg: "进入房间", url: answerUrl})

        } catch (e) {
            console.error("share err is", e);
            return cb({code: 500, msg: "error"})
        }
    }

    async getAnswerRoom(req, res, cb) {
        try {
            let body = req.body;

            let roomInfo = await sqlOrm.roomInfo.findAsync({status:1});

            if(roomInfo.length <= 0) return cb({code: 500, msg: "没有房间信息"});

            return cb({code: 200, msg: "成功", roomInfo: roomInfo})

        } catch (e) {
            console.error("share err is", e);
            return cb({code: 500, msg: "error"})
        }
    }

    /// 提现
    async transfer(req, res, body, cb) {
        try {
            // let signData = req.body.data;
            // let chechInfo = chechSing(signData)
            // if (chechInfo.code != 200) return cb(chechInfo);
            // let signDecodedInfo = chechInfo.signDecodedInfo

            let amount = JSON.parse(body.money);
            let account = body.account;
            let channel = body.channel;
            let app_id = body.app_id;
            let token = body.token;
            if (amount < 500){
                return cb({code: 500,  msg: "5元以上可以提现", token: token});
            }
            if(amount > 5000){
                return cb({code: 500,  msg: "每日提现金额上限为 "+ global.MaxMoney/100 +" 元", token: token});
            }

            let sumMoney = await sqlOrm.connectionLocalhot.execQueryAsync( "SELECT sum(money) sumMayPay FROM transfer WHERE PayAccount = ? and status = 1 and TO_DAYS(time) = TO_DAYS(now())", [account])
            if(sumMoney.length >0 ){
                if(sumMoney[0].sumMayPay >=  global.MaxMoney )  {
                    return cb({code: 500,  msg: "每日提现金额上限为 "+ global.MaxMoney/100 +" 元", token: token});
                }

                if( JSON.parse(sumMoney[0].sumMayPay) + JSON.parse(amount) >=  global.MaxMoney )  {
                    return cb({code: 500,  msg: "每日提现金额上限为 "+ global.MaxMoney/100 +" 元", token: token});
                }
            }

            let AccountInfo = await sqlOrm.app_account.findAsync({account:account});
            if(AccountInfo.length <= 0){
                return cb({code: 500,  msg: "账号不存在", token: token});
            }

            if(AccountInfo[0].blackUser == 1){
                console.error("被拉黑的人无法体现")
                return cb({code: 500,  msg: "账号异常", token: token});
            }

            if(AccountInfo[0].aliAccount.length <= 0){
                return cb({code: 500,  msg: "请绑定支付宝账号后提现", token: token});
            }


            let money = AccountInfo[0].money;
            if(money < amount  ) return cb({code: 500,  msg: "金额不足", token: token});

            let orderId = uuid.v4().substring(0,31);
            let data = {}

            data.amount = amount ;
            data.account = AccountInfo[0].aliAccount;
            data.channel = channel;
            data.app_id = app_id;
            /// 保存订单
            data.out_biz_no = orderId;

            let transfer = await RequestPost(transferUrl,data)
            transfer = utils.changeToObj(transfer)
            console.log("transfer",transfer)
            let newOrder = await  sqlOrm.transfer.createAsync({channel,money:amount,PayAccount:account,AccountID:account,orderId:orderId,status:0,time:new Date().toLocaleString(),aliAccount: data.account});
            console.log("newOrder",newOrder)
            if(transfer.alipay_fund_trans_toaccount_transfer_response.code == 10000){
                AccountInfo[0].money -= amount
                AccountInfo[0].moneyBake += amount
                AccountInfo[0].saveAsync();
                let transferInfo = await sqlOrm.transfer.findAsync({orderId})
                transferInfo[0].status = 1;
                transferInfo[0].saveAsync();
                return cb({code: 200, msg: "成功"})
            }else if(transfer.alipay_fund_trans_toaccount_transfer_response.sub_code ==  "PAYEE_NOT_EXIST") {
                return cb({code: 500, msg: "转账失败，请确定支付宝账号是否正确"})
            }else if(transfer.alipay_fund_trans_toaccount_transfer_response.sub_code ==  "PAYEE_ACC_OCUPIED") {
                return cb({code: 500, msg: "该手机号对应多个支付宝账户，请传入收款方姓名确定正确的收款账号"})
            }else {
                console.error("转账失败",transfer)
                return cb({code: 500, msg: "转账失败，请稍后重试"})
            }
        } catch (e) {
            console.error("transfererris", e);
            return cb({code: 500, msg: "sorry 转账失败，请稍后重试"})
        }
    }


    async getCutNum (req, res, next) {
        let body = req.query;
        try {
            const { token ,MacId} = body;
            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            if (JsonString.code == 200) {
                const decodedInfo = JSON.parse(JsonString.decoded);
                console.log("decodedInfo", decodedInfo)
                const id = decodedInfo.id;
                let AccountInfo = await sqlOrm.app_account.findAsync({id});
                let cutNum = JSON.parse(AccountInfo[0].cutNum)
                if (cutNum > 0){
                    let JsonString = sea.encrypt(sea.key, sea.vi, JSON.stringify({id: AccountInfo[0].id,time:new Date().getTime(),Num:cutNum-1}));
                    let cutSign = new Buffer(JsonString).toString('base64');
                    AccountInfo[0].cutNum -= 1
                    AccountInfo[0].saveAsync()


                    res.json({code: 200, cutNum:cutNum,cutSign:cutSign});
                }else {
                    res.json({code: 500});
                }
            }
        } catch (e) {
            console.error("saveAnswerList 采集答案失败" ,new Date().toLocaleString(), e);
            res.json({code: 500});
        }
    }


    async signUp (req, res, cb) {
        try {
            let signData = req.body.data;
            let chechInfo = chechSing(signData)
            if (chechInfo.code != 200) return cb(chechInfo);

            let signDecodedInfo = chechInfo.signDecodedInfo;
            let token = signDecodedInfo.token;
            if (!token) return cb({code: 500, msg: "参数不足"})
            let JsonString = sea.decrypt(sea.key, sea.vi, token);
            if (typeof JsonString === 'string')
                JsonString = JSON.parse(JsonString);
            console.log("JsonString", JsonString)
            if (JsonString.code != 200) {
                return cb({code: 500, msg: "签名错误"})
            }

            const decodedInfo = JSON.parse(JsonString.decoded);
            console.log("decodedInfo", decodedInfo)
            const id = decodedInfo.id;
            let AccountInfo = await sqlOrm.app_account.findAsync({id});
            if (AccountInfo.length <= 0)  return cb({code: 500, msg: "没有账号信息"})

            let isVip = 0
            if (JSON.parse(AccountInfo[0].time) + JSON.parse(AccountInfo[0].aliveTime) * (1000 * 60 * 60 * 24 ) < new Date().getTime()) {
                isVip = 1
            }

            let signUp = await sqlOrm.signUp.findAsync({isVip:isVip});
            let singCount = signUp.value

            // 修改签到时间
            let signUpTime  = AccountInfo[0].signUpTime;
            if(new Date().getTime() - JSON.parse(signUpTime) < 24 * 60 * 60 * 1000){
                return cb({code: 500, msg: "时间没到无法签到"})
            }

            AccountInfo[0].signUpTime = new Date().getTime()
            AccountInfo[0].cutNum += singCount;
            AccountInfo[0].saveAsync();
            return cb({code: 200, msg: "签到成功"})
        }catch (e) {
            console.error("signUp 签到失败" ,new Date().toLocaleString(), e);
            cb({code: 500});
        }
    }


    async sentNotifyMsg (feq,res,cb){

        try {
            var pass = req.query;
            if (pass != "wengchaoan"){
                return cb({code:500,msg:"passWd is false"})
            }
            let AccountInfo = await sqlOrm.app_account.findAsync({});
            for (i of AccountInfo){
                if(i.phone) {
                    var msgInfo = JSON.stringify({name :"msgInfo"});
                   await sentMsgInfo(i.phone, 'SMS_128840469', msgInfo);
                }
            }
            cb({code:200,code,msg:"成功"})
        }catch (e) {
            cb({code:500,msg:"发送失败"})
        }

    }
}

function compare(property) {
    return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}

async function sentMsgInfo(PhoneNumbers, TemplateCode, TemplateParam) {
    try {
        const msgRes = await smsClient.sendSMS({
            PhoneNumbers,
            SignName: mySignName,
            TemplateCode,
            TemplateParam,
        });
        // console.log("44444444444", msgRes);
        let res = {code: 500, info: '验证码发送失败'};
        if (msgRes.Code === 'OK') res = {code: 200, info: '验证码发送成功'};
        return res;
    } catch (e) {
        return {code: 500, info: e};
    }
}

async function getrandomNumber(num) {
    try {
        let code = '';
        for (let i = 0; i < num; i++) {
            code += Math.floor(Math.random() * 10);
        }
        return {code: 200, info: code};
    } catch (e) {
        return {code: 500};
    }
}

async function bindVip(MacId, account, passWd, phone) {
    try {
        console.log("bindVipbindVipbindVip", MacId)
        MacId = decodeURIComponent(MacId)
        let vipInfo = await sqlOrm.account.findAsync({account: MacId, status: 0})
        if (vipInfo.length <= 0) {
            return ({code: 500, msg: "不是vip"});
        } else {
            vipInfo[0].status = -2;
            vipInfo[0].saveAsync()
            return ({code: 200, data: vipInfo[0]});
        }
    } catch (e) {
        console.error("getTime err is", e);
        if (!e) e = "err"
        return cb({code: 500, msg: e})
    }
}

function chechSing(signData) {
    try {
        let signDataString = sea.decrypt(sea.key, sea.vi, signData);
        if (typeof signDataString === 'string') signDataString = JSON.parse(signDataString);
        if (signDataString.code != 200)  return ({code: 500, msg: "加密错误1"});
        const signDecodedInfo = JSON.parse(signDataString.decoded);
        let sign = signDecodedInfo.sign;
        let MacId = signDecodedInfo.MacId;

        let sign_ = sea.decrypt(sea.key, sea.vi, sign)
        if (sign_.code != 200)  return ({code: 500, msg: "加密错误2"})
        const sign_decoded = JSON.parse(sign_.decoded);
        if (sign_decoded.MacId != MacId + "jinyu") return ({code: 500, msg: "macId 错误"})
        if (parseInt(new Date().getTime()) - JSON.parse(sign_decoded.time) >= 1000 * 60 * 2) return ({
            code: 500,
            msg: "时间错误"
        });
        return {code: 200, signDecodedInfo: signDecodedInfo}
    } catch (e) {
        return ({code: 500, msg: "错误"})
    }
}

module.exports = new Register();
